package thoven.achievement.net.jsonutil.toolwindow

import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextArea
import com.intellij.util.ui.JBUI
import thoven.achievement.net.jsonutil.service.JsonCleaner
import thoven.achievement.net.jsonutil.service.JsonFormatter
import thoven.achievement.net.jsonutil.ui.JsonTreeViewer
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import javax.swing.*

/**
 * JSON 工具窗口主面板
 */
class JsonToolWindowPanel(private val project: Project) : JPanel(BorderLayout()) {
    
    private val inputArea = JBTextArea()
    private val outputArea = JBTextArea()
    private val treeViewer = JsonTreeViewer()
    
    init {
        setupUI()
    }
    
    private fun setupUI() {
        // 顶部工具栏
        val toolBar = createToolBar()
        add(toolBar, BorderLayout.NORTH)
        
        // 中间分割面板
        val splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        
        // 上半部分：输入/输出文本区
        val textPanel = createTextPanel()
        splitPane.topComponent = textPanel
        
        // 下半部分：树形视图
        val treePanel = createTreePanel()
        splitPane.bottomComponent = treePanel
        
        splitPane.resizeWeight = 0.5
        splitPane.dividerLocation = 300
        
        add(splitPane, BorderLayout.CENTER)
    }
    
    private fun createToolBar(): JPanel {
        val panel = JPanel(GridBagLayout())
        panel.border = JBUI.Borders.empty(5)
        
        val gbc = GridBagConstraints()
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.insets = JBUI.insets(0, 5)
        
        // 格式化按钮
        val formatBtn = JButton("格式化").apply {
            addActionListener { formatJson() }
        }
        panel.add(formatBtn, gbc)
        
        // 压缩按钮
        val compactBtn = JButton("压缩").apply {
            addActionListener { compactJson() }
        }
        panel.add(compactBtn, gbc)
        
        // 清理按钮
        val cleanBtn = JButton("清理修复").apply {
            addActionListener { cleanJson() }
        }
        panel.add(cleanBtn, gbc)
        
        // 解转义按钮
        val unescapeBtn = JButton("解转义").apply {
            addActionListener { unescapeJson() }
        }
        panel.add(unescapeBtn, gbc)
        
        // 转义按钮
        val escapeBtn = JButton("转义").apply {
            addActionListener { escapeJson() }
        }
        panel.add(escapeBtn, gbc)
        
        // 验证按钮
        val validateBtn = JButton("验证").apply {
            addActionListener { validateJson() }
        }
        panel.add(validateBtn, gbc)
        
        // 清空按钮
        val clearBtn = JButton("清空").apply {
            addActionListener { clearAll() }
        }
        panel.add(clearBtn, gbc)
        
        // 填充剩余空间
        gbc.weightx = 1.0
        panel.add(Box.createHorizontalGlue(), gbc)
        
        return panel
    }
    
    private fun createTextPanel(): JPanel {
        val panel = JPanel(GridBagLayout())
        val gbc = GridBagConstraints()
        gbc.fill = GridBagConstraints.BOTH
        gbc.weightx = 0.5
        gbc.weighty = 1.0
        gbc.insets = JBUI.insets(5)
        
        // 输入区
        gbc.gridx = 0
        val inputPanel = JPanel(BorderLayout())
        inputPanel.border = BorderFactory.createTitledBorder("输入 JSON")
        inputArea.lineWrap = true
        inputArea.wrapStyleWord = true
        inputPanel.add(JBScrollPane(inputArea), BorderLayout.CENTER)
        panel.add(inputPanel, gbc)
        
        // 输出区
        gbc.gridx = 1
        val outputPanel = JPanel(BorderLayout())
        outputPanel.border = BorderFactory.createTitledBorder("输出结果")
        outputArea.lineWrap = true
        outputArea.wrapStyleWord = true
        outputArea.isEditable = false
        outputPanel.add(JBScrollPane(outputArea), BorderLayout.CENTER)
        panel.add(outputPanel, gbc)
        
        return panel
    }
    
    private fun createTreePanel(): JPanel {
        val panel = JPanel(BorderLayout())
        panel.border = BorderFactory.createTitledBorder("树形视图")
        panel.add(treeViewer, BorderLayout.CENTER)
        return panel
    }
    
    private fun formatJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        val cleanResult = JsonCleaner.clean(input)
        if (cleanResult.isFailure) {
            Messages.showErrorDialog(project, "清理失败: ${cleanResult.exceptionOrNull()?.message}", "错误")
            return
        }
        
        val result = JsonFormatter.format(cleanResult.getOrNull() ?: "")
        if (result.isSuccess) {
            val formatted = result.getOrNull() ?: ""
            outputArea.text = formatted
            treeViewer.displayJson(formatted)
        } else {
            Messages.showErrorDialog(project, "格式化失败: ${result.exceptionOrNull()?.message}", "错误")
        }
    }
    
    private fun compactJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        val cleanResult = JsonCleaner.clean(input)
        if (cleanResult.isFailure) {
            Messages.showErrorDialog(project, "清理失败: ${cleanResult.exceptionOrNull()?.message}", "错误")
            return
        }
        
        val result = JsonFormatter.compact(cleanResult.getOrNull() ?: "")
        if (result.isSuccess) {
            outputArea.text = result.getOrNull()
            treeViewer.clear()
        } else {
            Messages.showErrorDialog(project, "压缩失败: ${result.exceptionOrNull()?.message}", "错误")
        }
    }
    
    private fun cleanJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        val result = JsonCleaner.clean(input)
        if (result.isSuccess) {
            outputArea.text = result.getOrNull()
        } else {
            Messages.showErrorDialog(project, "清理失败: ${result.exceptionOrNull()?.message}", "错误")
        }
    }
    
    private fun unescapeJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        outputArea.text = JsonCleaner.unescapeJson(input)
    }
    
    private fun escapeJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        outputArea.text = JsonCleaner.escapeJson(input)
    }
    
    private fun validateJson() {
        val input = inputArea.text.trim()
        if (input.isEmpty()) {
            Messages.showWarningDialog(project, "请输入 JSON 内容", "提示")
            return
        }
        
        val result = JsonFormatter.validate(input)
        if (result.isSuccess) {
            Messages.showInfoMessage(project, "JSON 格式正确！", "验证成功")
        } else {
            Messages.showErrorDialog(project, "JSON 格式错误: ${result.exceptionOrNull()?.message}", "验证失败")
        }
    }
    
    private fun clearAll() {
        inputArea.text = ""
        outputArea.text = ""
        treeViewer.clear()
    }
}

